<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小同住人员物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\room;

use think\App;
use app\controller\property\Base;
use think\exception\ValidateException;
use app\validate\room\RoomBasicValidate;
use app\common\repositories\room\RoomLogRepository;
use app\common\repositories\room\RoomLabelRepository;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\energy\EnergyMeterRepository;
use app\common\repositories\property\basic\PropertyUnitRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;


class RoomBasic extends Base
{
    protected $repository;

    public function __construct(App $app, RoomBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyRoomBasicAdd'),
            'editAuth' => property_auth('propertyRoomBasicEdit'),
            'delAuth' => property_auth('propertyRoomBasicDel'),
            'copyAuth' => property_auth('propertyRoomBasicCopy'),
            'detailAuth' => property_auth('propertyRoomBasicDetail'),
        ]);
    }

    protected function commonParams()
    {
        /** @var PropertyBasicRepository $propertyBasicRepository */
        $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
        $propertyData = $propertyBasicRepository->getUserAllPropertyList($this->request->userId);
        $this->assign([
            'propertyData' => $propertyData,
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'contract_id' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getPropertyList($where, $page, $limit);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }

        /** @var PropertyBasicRepository $propertyBasicRepository */
        $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
        $propertyData = $propertyBasicRepository->getUserAllPropertyList($this->request->userId);
        return $this->fetch('room/basic/list', [
            'propertyData' => $propertyData,
        ]);
    }

    public function add()
    {
        $propertyId = $this->request->param('property_id');
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'unitData') {
            /** @var PropertyUnitRepository $propertyUnitRepository */
            $propertyUnitRepository = app()->make(PropertyUnitRepository::class);
            $topData = $propertyUnitRepository->getSearch([])
                ->where('is_show', 1)
                ->where('property_id', $propertyId)
                ->append(['full_unit_name'])
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $topData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'property_id' => '',
                'unit_id' => '',
                'floor_name' => '',
                'floor_total' => '',
                'room_name' => '',
                'room_unit' => '',
                'room_num' => '',
                'hall_num' => '',
                'who_num' => '',
                'room_size' => '',
                'room_rent' => '',
                'room_deposit' => '',
                'property_fee' => '',
                'direction' => '',
                'label_id' => '',
                'remark' => '',
                'picture' => ''
            ]);
            validate(RoomBasicValidate::class)->scene('add')->check($param);
            if ($this->repository->roomNameExists($param['property_id'], $param['room_name'], (int)$param['unit_id'])) {
                return $this->error('房间' . $param['room_name'] . '已存在');
            }
            try {
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $res = $this->repository->addInfo($param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加房间失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $this->commonParams();
            /** @var PropertyUnitRepository $propertyUnitRepository */
            $propertyUnitRepository = app()->make(PropertyUnitRepository::class);
            $topData = $propertyUnitRepository->getSearch([])
                ->where('is_show', 1)
                ->where('property_id', $this->request->propertyId)
                ->append(['full_unit_name'])
                ->select()->toArray();
            /** @var RoomLabelRepository $roomLabelRepository */
            $roomLabelRepository = app()->make(RoomLabelRepository::class);
            $labelData = $roomLabelRepository->getLabelData(['is_show' => 1]);
            return $this->fetch('room/basic/add', [
                'topData' => $topData,
                'labelData' => $labelData,
                'propertyId' => $propertyId,
            ]);
        }
    }

    public function copy()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'property_id' => '',
                'floor_name' => '',
                'floor_total' => '',
                'room_name' => '',
                'room_unit' => '',
                'room_num' => '',
                'hall_num' => '',
                'who_num' => '',
                'room_size' => '',
                'room_rent' => '',
                'room_deposit' => '',
                'property_fee' => '',
                'remark' => '',
                'direction' => '',
                'label_id' => '',
                'picture' => ''
            ]);
            validate(RoomBasicValidate::class)->scene('edit')->check($param);
            if ($this->repository->roomNameExists($info['property_id'], $param['room_name'], (int)$info['unit_id'])) {
                return $this->error('房间' . $param['room_name'] . '已存在');
            }
            try {
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $param['add_uid'] = $this->request->userId;
                $res = $this->repository->copynfo($info, $param,  $this->request->userId);
                if ($res) {
                    return $this->success('复制成功');
                } else {
                    return $this->error('复制失败');
                }
            } catch (\Exception $e) {
                exception_log('复制房间失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            /** @var RoomLabelRepository $roomLabelRepository */
            $roomLabelRepository = app()->make(RoomLabelRepository::class);
            $labelData = $roomLabelRepository->getLabelData(['is_show' => 1]);
            return $this->fetch('room/basic/copy', [
                'info' => $info,
                'labelData' => $labelData,
            ]);
        }
    }


    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'floor_name' => '',
                'floor_total' => '',
                'room_name' => '',
                'room_unit' => '',
                'room_num' => '',
                'hall_num' => '',
                'who_num' => '',
                'room_size' => '',
                'room_rent' => '',
                'room_deposit' => '',
                'property_fee' => '',
                'label_id' => '',
                'remark' => '',
                'direction' => '',
                'picture' => ''
            ]);
            validate(RoomBasicValidate::class)->scene('edit')->check($param);
            if ($this->repository->roomNameExists($info['property_id'], $param['room_name'], (int)$info['unit_id'], $info['id'])) {
                return $this->error('房间' . $param['room_name'] . '已存在');
            }
            try {
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改房间失败', $e);
                return $this->error('网络错误');
            }
        } else {
            /** @var RoomLabelRepository $roomLabelRepository */
            $roomLabelRepository = app()->make(RoomLabelRepository::class);
            $labelData = $roomLabelRepository->getLabelData(['is_show' => 1]);
            return $this->fetch('room/basic/edit', [
                'info' => $info,
                'labelData' => $labelData,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除房间失败', $e);
            return $this->error('网络失败');
        }
    }

    public function detail()
    {
        $roomId = (int)$this->request->param('room_id');
        if ($roomId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($roomId);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('room/basic/detail', [
            'info' => $info,
            'bindAuth' => property_auth('propertyRoomBindEnergyMeter'),
            'unbindAuth' => property_auth('propertyRoomUnbindEnergy'),
            'rechargeAuth' => property_auth('propertyEnergyMeterRecharge'),
        ]);
    }


    /**
     * 能源设备绑定
     * @param EnergyMeterRepository $energyMeterRepository
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-09 18:42
     */
    public function bindEnergyMeter(EnergyMeterRepository $energyMeterRepository)
    {
        $roomId = (int)$this->request->param('room_id');
        if (!$roomId) {
            return $this->error('参数错误');
        }
        if (!$this->repository->propertyExists($this->request->propertyId, $roomId)) {
            return $this->error('数据不存在');
        }
        $roomInfo = $this->repository->get($roomId);
        if (!$roomInfo) {
            throw new ValidateException('房间不存在');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'meter_id' => '',
                'remark' => '',
            ]);
            $param['property_id'] = $roomInfo['property_id'];
            $energyMeterRepository->bindRoom($param, $roomId, $this->request->userId);
            return $this->success('绑定成功');
        } else {
            $meterList = $energyMeterRepository->getMeterData($this->request->propertyId, [
                'room_id' => 0,
                'is_bind' => 2,
                'is_public' => 2,
                'property_id' => $roomInfo['property_id']
            ]);
            return $this->fetch('room/basic/bing_energy', [
                'info' => $roomInfo,
                'meterList' => $meterList,
            ]);
        }
    }


    /**
     * 能源设备解除
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-09 23:08
     */
    public function unbindEnergyMeter(EnergyMeterRepository $energyMeterRepository)
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $remark = $this->request->param('remark');
        if ($remark == '') {
            return $this->error('请输入解绑原因');
        }
        $info = $energyMeterRepository->get($id);
        if ($info['id'] <= 0) {
            return $this->error('设备不存在');
        }
        $energyMeterRepository->unbindByInfo($info, $remark, $this->request->userId);
        return $this->success('解绑成功');
    }


    /**
     * 房间日志
     * @param RoomLogRepository $logRepository
     * @return \think\response\Json|void
     *
     * @author Amos
     * 2024-05-09 18:37
     */

    public function roomLog(RoomLogRepository $logRepository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'room_id' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $logRepository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }


}